/**
 * Application business handler
 */

var config = require('../config');
var db = config.db;
var utils = require('../utils');
var moment = require('moment');
moment.lang('zh-cn');


// login
exports.login = function(req, resp, next) {
    var cuid = req.cookies.uid;
    if (cuid != null && '' != cuid) {
        resp.redirect('index');
    } else {
        // TODO
    }
    // TODO
    resp.render('login');
};
// login action
exports.login_do = function(req, resp, next) {
    var uid = req.body.uid;
    var uid = req.body.pwd;
    
    resp.render('login');
};


// question index page
exports.question = function(req, resp, next) {
    db.query('select * from t100_question order by status asc, qid desc limit 50', function(err, rows) {
        if (err) {
            return next(err);
        }

        utils.fnEach(rows, function(row) {
            row.post_date_disp = moment(row.post_date).fromNow();
        });

        resp.render('index', {
            faqs: rows
        });
    });
};

// add a new question
exports.question_new = function(req, resp, next) {
    var content = req.body.content || '';
    content = content.trim();
    if(!content) {
        return resp.render('error', {message: '请输入问题内容!咋这么懒呢？'});
    }
    var sql = 'insert into t100_question set content=?,asker=?,post_date=now()';
    var args = [content, "10001"];
    db.query(sql, args, function(err, result) {
        if (err) {
            return next(err);
        }
        resp.redirect('/faq/question');
    });
};

// reply
exports.reply = function(req, resp, next) {
    var qid = req.params.id;
    db.query('select * from t100_question where qid=?',[qid], function(err, questions) {
        if (err) { return next(err); }
        
        utils.fnEach(questions, function(row) {
            row.post_date_disp = moment(row.post_date).fromNow();
        });
        
        db.query('select * from t101_reply where qid=? order by reply_date desc', [qid], function(err, replys) {
            if (err) { return next(err); }
            // format reply date
            utils.fnEach(replys, function(row) {
                row.reply_date_disp = moment(row.reply_date).fromNow();
            });
            resp.render('reply', {
                faq: questions[0],
                replys: replys
            });
        });
    });
};

// add a new reply
exports.reply_new = function(req, resp, next) {
    var content = req.body.content || '';
    content = content.trim();
    if(!content) {
        return resp.render('error', {message: '请输入问题内容!'});
    }

    var qid = req.params.id;
    var sql = 'insert into t101_reply set qid=?, content=?, replier=?, reply_date=now()';
    var args = [qid, content, '10001'];
    db.query(sql, args, function(err, result) {
        if (err) { return next(err); }
        resp.redirect('/faq/' + qid + '/reply');
    });
};




